package com.game.sdk.pay.yxbpay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.text.TextUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.game.sdk.YTAppService;
import com.game.sdk.domain.PaymentCallbackInfo;
import com.game.sdk.domain.PaymentErrorMsg;
import com.game.sdk.domain.ResultCode;
import com.game.sdk.init.NetCallBack;
import com.game.sdk.ui.ChargeActivity;
import com.game.sdk.util.ActivityTaskManager;
import com.game.sdk.util.Constants;
import com.game.sdk.util.DialogUtil;
import com.game.sdk.util.GetDataImpl;
import com.game.sdk.util.Logger;
import com.game.sdk.util.MResource;
import com.game.sdk.util.Md5Util;
import com.game.sdk.util.Util;
import com.game.sdk.view.ChargeView;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class GameCurrencyActivity extends Activity implements OnClickListener {
	private TextView tv_refresh, tv_ttb_rest, tv_ttb_tip, tv_ptb_username,
			et_money, tv_pay, tv_back, tv_charge_title;
	private Context ctx;
	private double charge_money;// 需要充值的金额
	private String serverid;// 充值的服务器id；
	private String productname;// 充值游戏名称
	private String productdesc;// 产品描述
	private String fcallbackurl;// 充值回调地址，由游戏方传递
	private String roleid;// 角色id；
	private String attach;// 游戏方传递的拓展参数
	private long lasttime;// 防止用户点击刷新
	private String sign;

	private String allMoney;
	private String pay_id;
	private String order_id;
	private String pay_token;
	private String pt_name ="游戏币";
	private TextView pt_name_tv;
	private Handler mHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(MResource.getIdByName(this, Constants.Resouce.LAYOUT,
				"sdk_game_pay"));
		this.ctx = getApplicationContext();
		Intent intent = getIntent();
		roleid = intent.getStringExtra("roleid");
		serverid = intent.getStringExtra("serverid");
		charge_money = intent.getDoubleExtra("money", 0);
		productname = intent.getStringExtra("productname");
		productdesc = intent.getStringExtra("productdesc");
		fcallbackurl = intent.getStringExtra("fcallbackurl");
		attach = intent.getStringExtra("attach");

		pay_id = intent.getStringExtra("pay_id");
		order_id = intent.getStringExtra("order_id");
		pay_token = intent.getStringExtra("pay_token");
		pt_name = intent.getStringExtra("pt_name");
		init();
		super.onCreate(savedInstanceState);
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				DialogUtil.showDialog(GameCurrencyActivity.this, "刷新游戏币中");
				refreshTTB();
			}
		}, 30);
	}

	private void init() {

		et_money = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_ptb_money"));
		tv_pay = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_pay"));
		tv_refresh = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_refresh"));
		tv_ttb_rest = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_ttb_rest"));
		tv_ttb_tip = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_ttb_tip"));
		tv_ptb_username = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_ptb_username"));
		tv_charge_title = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_charge_title"));
		pt_name_tv = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_balance"));
		tv_charge_title.setOnClickListener(this);
		tv_back = (TextView) findViewById(MResource.getIdByName(ctx,
				Constants.Resouce.ID, "tv_back"));
		tv_back.setOnClickListener(this);

		tv_ptb_username.setText(YTAppService.userinfo.username);
		tv_ttb_rest.setText(String.valueOf(YTAppService.yxb));
		et_money.setText(charge_money + "元" + " (" + charge_money * YTAppService.ttbrate + pt_name+")");
		tv_ttb_tip.setText("1人民币=" +  YTAppService.ttbrate + pt_name+"");
		
		tv_charge_title.setText(pt_name+"支付");
		pt_name_tv.setText(pt_name+"余额");
		// init_btn_charge_color(charge_money * SDKService.ptbrate+"");
		et_money.setOnFocusChangeListener(fc_et_money);
		// et_money.addTextChangedListener(tw_et_money);
		et_money.setOnClickListener(this);
		tv_pay.setOnClickListener(this);
		tv_refresh.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		if (null != tv_back && v.getId() == tv_back.getId()) {
			Util.onPayReqFail("用户取消充值", charge_money, GameCurrencyActivity.this);
			return;
		}
		if (null != tv_charge_title && v.getId() == tv_charge_title.getId()) {
			Util.onPayReqFail("用户取消充值", charge_money, GameCurrencyActivity.this);
			return;
		}
		if (null != tv_pay && v.getId() == tv_pay.getId()) {
			int money = (int) (charge_money * YTAppService.ttbrate);
			DialogUtil.showDialog(GameCurrencyActivity.this, "正在充值中...");
			NetUtil.reqYxbpay(YTAppService.userinfo.mem_id,
					YTAppService.userinfo.user_token, charge_money + "",
					pay_token, money + "", ctx, new NetCallBack() {

						@Override
						public void onInitSuccess(ResultCode result) {
							String data = result.data;
							if (!TextUtils.isEmpty(data)) {
								JSONObject o;
								try {
									o = new JSONObject(data);
									order_id = (String) o.get("a");
									ChargeView.ischarge = true;
									PaymentCallbackInfo pci = new PaymentCallbackInfo();
									pci.money = charge_money;
									pci.msg = "充值成功";
									ChargeActivity.paymentListener
											.paymentSuccess(pci);
									showDialog((null != result && result.code == 1) ? "游戏币充值成功,谢谢您的支持！"
											: "充值失败！请联系客服\n QQ:"
													+ YTAppService.service_qq
													+ " \n Tel:"
													+ YTAppService.service_tel);
									/**
									 * 支付成功后刷新币
									 */
									Intent app_intent = new Intent(ctx,
											YTAppService.class);
									app_intent.putExtra("login_success",
											"login_success");
									ctx.startService(app_intent);
									return;
								} catch (JSONException e) {
									Util.showNetFailToast(ctx, "数据转化异常340",
											null);
								}
							} else {
								Util.showNetFailToast(ctx, "支付的时候异常", null);
							}
							Util.onPayReqFail("支付失败", charge_money,
									GameCurrencyActivity.this);
						}

						@Override
						public void onInitFail(ResultCode result) {
							if (result != null && result.code == -15) {
								Util.showNetFailToast(
										GameCurrencyActivity.this, "余额不足",
										result);
								return;
							}
							Util.onPayReqFail("充值失败", charge_money,
									GameCurrencyActivity.this);
						}
					});
		}
		if (null != tv_refresh && v.getId() == tv_refresh.getId()) {
			refreshTTB();
			return;
		}
	}

	private OnFocusChangeListener fc_et_money = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
		}
	};

	private void init_btn_charge_color(String s) {
		if (TextUtils.isEmpty(s) || "".equals(s) || !s.matches("[0-9]+")) {
			tv_pay.setBackgroundColor(ctx.getResources().getColor(
					MResource.getIdByName(ctx, "color", "btn_charge_gray")));
		} else {
			int money = Integer.parseInt(s);
			charge_money = money;
			tv_pay.setBackgroundColor(ctx.getResources().getColor(
					MResource
							.getIdByName(ctx, "color",
									money == 0 ? "btn_charge_gray"
											: "btn_charge_green")));
		}
	}

	private Dialog dialog;

	/**
	 * 充值时显示的对话框
	 */
	private void showDialog(String msg) {
		dialog = new Dialog(GameCurrencyActivity.this, MResource.getIdByName(
				ctx, "style", "customDialog"));
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		// View
		// view=getLayoutInflater().inflate(R.layout.tiantianwan_order_fail,null);
		View view = LayoutInflater.from(this).inflate(
				MResource.getIdByName(ctx, "layout", "sdk_tell_service"), null);
		view.findViewById(MResource.getIdByName(ctx, "id", "tv_tip"))
				.setVisibility(View.GONE);
		((TextView) view
				.findViewById(MResource.getIdByName(ctx, "id", "tv_qq")))
				.setText(msg);
		((TextView) view.findViewById(MResource
				.getIdByName(ctx, "id", "tv_tel"))).setVisibility(View.GONE);

		((TextView) view.findViewById(MResource.getIdByName(ctx, "id",
				"tv_orderid_title"))).setVisibility(View.GONE);
		((TextView) view.findViewById(MResource.getIdByName(ctx, "id",
				"tv_orderid_title1"))).setVisibility(View.GONE);
		view.findViewById(MResource.getIdByName(ctx, "id", "btn_sure"))
				.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
						dialog = null;
						GameCurrencyActivity.this.finish();
						ActivityTaskManager.getInstance().removeActivity(
								"ChargeActivity");
					}
				});
		dialog.setContentView(view);
		dialog.show();
	};

	private int count = 1;

	/**
	 * 刷新易通币
	 */
	private void refreshTTB() {
		if (System.currentTimeMillis() - lasttime <= 3000) {
			if (count > 1) {
				Toast.makeText(ctx, "您点击频率太快，请休息几秒钟", Toast.LENGTH_SHORT)
						.show();
			}
			count++;
			return;
		}
		NetUtil.getYxb(YTAppService.userinfo.mem_id,
				YTAppService.userinfo.user_token, ctx, new NetCallBack() {

					@Override
					public void onInitSuccess(ResultCode result) {
						String data = result.data;
						if (!TextUtils.isEmpty(data)) {
							JSONObject o;
							try {
								o = new JSONObject(data);
								allMoney = o.getString("a");
								tv_ttb_rest.setText(allMoney.toString());// 设置平台币数目
								Util.showNetFailToast(
										GameCurrencyActivity.this, "刷新游戏币成功",
										null);
								lasttime = System.currentTimeMillis();
								count = 1;
							} catch (Exception e) {
								Util.showNetFailToast(
										GameCurrencyActivity.this, "数据转化异常340",
										null);
							}
						} else {
							Util.showNetFailToast(GameCurrencyActivity.this,
									"获取游戏币失败", result);
						}
					}

					@Override
					public void onInitFail(ResultCode result) {
						Util.showNetFailToast(GameCurrencyActivity.this,
								"没能获取到数据", result);
						GameCurrencyActivity.this.finish();
						ActivityTaskManager.getInstance().removeActivity(
								"ChargeActivity");
					}
				});

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		super.onDestroy();

	}
}
